import Redis from 'ioredis';
import { isNil, isString } from 'lodash-es';

class RedisWrapper {
  private _client: Redis;
  private initialize() {
    this._client = global.redis; // 初始化Redis客户端
  }

  get<T>(key): Promise<T> {
    this.initialize();
    return new Promise((resolve, reject) => {
      this._client.get(key, (err, reply) => {
        if (err) {
          reject(err);
        } else {
          if (!isNil(reply) && isString(reply)) {
            resolve(JSON.parse(reply));
          } else {
            resolve(false);
          }
        }
      });
    });
  }

  set(key, value) {
    this.initialize();
    return new Promise((resolve, reject) => {
      this._client.set(key, JSON.stringify(value), (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(true);
        }
      });
    });
  }
  remove(key) {
    this.initialize();
    return new Promise((resolve, reject) => {
      this._client.del(key, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(true);
        }
      });
    });
  }
}
export default new RedisWrapper();
